import pandas as pd

bitcoin_remained = 500
bitcoin_buy = 0
bitcoin_value = 500

gold_remained = 500
gold_buy = 0
gold_value = 500

gold_mid_price = 0.01
bitcoin_mid_price = 0.02

# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    # 导入数据
    data = pd.read_excel("data/data_2_1.xlsx")
    print(data)
    bitcoin_prices = data['bitcoin_prices'].values
    # print(bitcoin_prices)
    gold_prices = data['gold_prices'].values
    bitcoin_decision = data['bitcoin_decision'].values
    gold_decision = data['gold_decision'].values
    bitcoin_proportion = data['bitcoin_proportion'].values
    gold_proportion = data['gold_proportion'].values
    # print(gold_proportion)
    past_bit_value = bitcoin_prices[0]
    past_gold_value = gold_prices[0]

    temp = []

    for i in range(len(data)):
        # 更新买入市值
        bitcoin_buy *= bitcoin_prices[i] / past_bit_value
        past_bit_value = bitcoin_prices[i]
        gold_buy *= gold_prices[i] / past_gold_value
        past_gold_value = gold_prices[i]

        # 更新市值
        bitcoin_value = bitcoin_buy + bitcoin_remained
        gold_value = gold_buy + gold_remained
        total_value = bitcoin_value + gold_value

        # 根据比例重分配余量
        bit_new = total_value*bitcoin_proportion[i]
        diff = bitcoin_value-bit_new
        if diff >= 0:
            if bitcoin_remained > diff:
                gold_remained += diff
                bitcoin_remained -= diff
            else:
                gold_remained += bitcoin_remained
                bitcoin_remained = 0
        else:
            diff = - diff
            if gold_remained > diff:
                bitcoin_remained += diff
                gold_remained -= diff
            else:
                bitcoin_remained += gold_remained
                gold_remained = 0
        print("更新分配：")
        print(bitcoin_remained, gold_remained)

        # 判断是否购买或卖出比特币
        if bitcoin_decision[i] == 1:
            bitcoin_buy += bitcoin_remained * (1 - bitcoin_mid_price)
            bitcoin_remained = 0
            print('买入比特币', i)
        if bitcoin_decision[i] == 0:
            bitcoin_remained += bitcoin_buy * (1 - bitcoin_mid_price)
            bitcoin_buy = 0
            print('卖出比特币', i)

        if gold_decision[i] == 1:
            gold_buy += gold_remained * (1 - gold_mid_price)
            gold_remained = 0
            print('买入黄金', i)
        if gold_decision[i] == 0:
            gold_remained += gold_buy * (1 - gold_mid_price)
            gold_buy = 0
            print('卖出黄金', i)

        temp.append([total_value,bitcoin_value, bitcoin_buy, bitcoin_remained, gold_value, gold_buy, gold_remained])

    temp = pd.DataFrame(temp, columns=['total_value', 'bitcoin_value', 'bitcoin_buy', 'bitcoin_remained', 'gold_value', 'gold_buy'
        , 'gold_remained'])

    temp.to_excel('save_2_1_learn.xlsx')
